-- UIBuyMaterial
-- Created by huanghr
-- 一键购买原料界面

UIBuyMaterial = class("UIBuyMaterial", function()
    return cc.Layer:create();
end);

-- 购买列表
function UIBuyMaterial.create(itemId, materialList)
    return UIBuyMaterial.new(itemId, materialList);
end

-- 每次最多可显示的购买原料种类
local MAX_BONUS_COUNT = 3;

-- 构造函数
function UIBuyMaterial:ctor(itemId, materialList)
    self:setName("UIBuyMaterial");
    local node = cc.CSLoader:createNode("layout/common/BonusNotify2.csb");
    self:addChild(node);
    self.node = node;

    -- 先把bonus的数据深拷贝出来，因为后面有可能会修改原料数据
    materialList = table.deepcopy(materialList);
    self.materialList = materialList;

    self.classId = itemId;

    self.canBuy = true;

    self:setCanBuy();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();

    self:registerEventCallBack();
end

-- 对奖励进行排序
function UIBuyMaterial:sortBonus(bonus)
    -- 按照奖励类型排序，物品在前，属性在后
    table.sort(bonus, function(a, b) return a[1] < b[1]; end);
    return bonus;
end

-- 重绘
function UIBuyMaterial:redraw()
    -- 设置标题
    local titleLabel = findChildByName(self.node, "CT/title");
    local titleStr = getLocStr("title_buy_material");
    TextStyleM.setTitleStyle(titleLabel);

    -- 正文样式
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 合成的是物品
    local itemName = ItemM.query(self.classId, "name");
    local str =  string.format(getLocStr("material_not_enough"), itemName);
    local costStr = getLocStr("cost_to_buy");
    if self.canBuy then
        local cost = FormulaM.invoke("CALC_BUY_MATERIAL_COST", self.materialList);
        -- TODO 都暂时认为只消耗一种，所以界面这里直接取第1个
        cost = cost[1];
        local name;
        local costNum = cost[3];
        if cost[1] == 2 then
            -- 属性
            name = FieldsM.query(cost[2], "name");
            if cost[2] == "gem" then
                -- 钻石要除以1000
                costNum = math.ceil(costNum / 1000);
            end
        else
            -- 道具
            name = ItemM.query(cost[2], "name");
            titleStr = string.format(getLocStr("title_buy_material2"), name);
            costStr = getLocStr("cost_to_exchange");
            local okBtn = findChildByName(self.node, "CT/btn_ok");
            okBtn:setTitleText(getLocStr("btn_text_one_exchange"));
        end
        -- 消耗信息
        str = str .. string.format(costStr, costNum, name);
    else
        str = str .. getLocStr("cant_buy_scrap");

        -- 设置按钮不可用
        local okBtn = findChildByName(self.node, "CT/btn_ok");
        okBtn:setBright(false);
        okBtn:setTouchEnabled(false);
    end

    local descLabel = applyString(descLabel, str);
    titleLabel:setString(titleStr);

    -- 需要替换角标图案为升级的
    local subBgLeft = findChildByName(self.node, "CT/sub_bg_l");
    local subBgRight = findChildByName(self.node, "CT/sub_bg_r");
    subBgLeft:loadTexture(getTitleBgIconPath("upgrade"));
    subBgRight:loadTexture(getTitleBgIconPath("upgrade"));

    self:redrawItem();

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg_frame");
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel");
    local okBtn = findChildByName(self.node, "CT/btn_ok");
    local descLabel = findChildByName(self.node, "CT/desc");

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_SMALL,
        { titleLabel, descLabel, bonusPanel, okBtn}, { 35, });

    -- 根据适配后的界面高度比例，对界面上的角标位置进行修正
    local bg1 = findChildByName(self.node, "CT/sub_bg_l");
    local bg2 = findChildByName(self.node, "CT/sub_bg_r");

    -- 这里要注意一下，原始的模版高度并不是100%，而是85%。。不解
    local fixY, deltaY = math.modf(AlignM.BG_SIZE_SMALL.height * (0.85 - bg:getScaleY()) / 2);

    if fixY > 0 then
        fixY = fixY + 9;
    else
        fixY = fixY + 10;
    end

    bg1:setPositionY(bg1:getPositionY() - fixY);
    bg2:setPositionY(bg2:getPositionY() - fixY);
end

function UIBuyMaterial:redrawItem()
    local parentNode = findChildByName(self.node, "CT/bonus_panel/bonus_node");

    -- 先清空
    parentNode:removeAllChildren();

    local item = cc.CSLoader:createNode("layout/item/CompoundItem.csb");
    item = replaceNodeWithWidget(item);

    local itemWidth = 100;
    local gap = 20;
    local widget = ccui.Widget:create();
    local totalWidth = #self.materialList * (itemWidth + gap);
    local itemsStr = "";
    local totalCount = #self.materialList;

    for i = 1, totalCount do
        local material = self.materialList[i];
        local classId = material.classId;
        local needNum = material.needNum;

        local child = item:clone();
        child:setPositionX((i - 1) * (itemWidth + gap));

        -- 图标
        local name;
        local iconPath;
        local scale = 0.8;
        local offsetY = 0;
        local icon = findChildByName(child, "item_icon");
        local iconPath = getItemIconPath(ItemM.query(classId, "icon"));

        icon:loadTexture(iconPath)
        icon:setPositionY(icon:getPositionY() + offsetY);

        icon:setScale(scale);

        -- 个数
        local countLabel = findChildByName(child, "item_num");
        countLabel:setVisible(true);
        countLabel:setPositionX(0);
        countLabel:setPositionY(-itemWidth/2 + 5);
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        countLabel:setString(tostring(needNum));

        widget:addChild(child);
    end

    widget:setPositionX(- totalWidth / 2 + (itemWidth + gap) / 2);
    parentNode:addChild(widget);
end

-- 注册点击事件
function UIBuyMaterial:registerTouchEvent()
    -- 确认按钮
    local okBtn = findChildByName(self.node, "CT/btn_ok");
    TextStyleM.setTextStyle(okBtn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    okBtn:setTitleText(self.okText or getLocStr("btn_text_buy_material"));

    -- 显示返回按钮
    local btNode = findChildByName(self.node, "BT");
    btNode:setVisible(true);
    local btnBack = findChildByName(self.node, "BT/btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    local function onCloseClick(sender, eventType)
       if eventType == ccui.TouchEventType.ended then
           AudioM.playFx("button_click");
            -- 检查是否足够购买
            local cost = FormulaM.invoke("CALC_BUY_MATERIAL_COST", self.materialList);
            -- TODO 都暂时认为只消耗一种，所以界面这里直接取第1个
            cost = cost[1];

            if cost[1] == 2 and cost[2] == "gem" then
                -- 钻石不足，打开钻石购买页面
                if ME.user:queryAttrib("gem") < math.ceil(cost[3]/1000) then
                    showGemLackConfirm();
                    return;
                end
            elseif cost[1] == 2 then
                if ME.user:queryAttrib(cost[2]) < cost[3] then
                    alert(string.format(getLocStr("not_enough"), FieldsM.query(cost[2], "name")));
                    return;
                end
            elseif cost[1] == 1 then
                if ItemM.getAmount(ME.user, cost[2]) < cost[3] then
                    alert(string.format(getLocStr("not_enough"), ItemM.query(cost[2], "name")));
                    return;
                end
            end

            -- 客户端购买，通知服务器
            Operation.cmd_one_click_buy(self.classId);
        end
    end
    okBtn:addTouchEventListener(onCloseClick);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            UIMgr.getCurrentScene():removeFormByName("UIBuyMaterial");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
end

-- 注册事件回调
function UIBuyMaterial:registerEventCallBack()
    -- 关注事件购买成功
    EventMgr.register("UIBuyMaterial", event.ONE_CLICK_BUY, function()
        -- 购买提示
        local str = "";
        for k, v in pairs(self.materialList) do
            local classId = v.classId;
            local itemName = ItemM.query(classId, "name");
            str = str.."\n" .. string.format(getLocStr("buy_goods_done"), itemName, v.needNum);
        end
        alert(str);

        UIMgr.getCurrentScene():removeFormByName("UIBuyMaterial");
    end);

    -- 关闭页面时刷新页面
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            -- 删除所有事件
            EventMgr.removeAll("UIBuyMaterial");
            local uiForm = UIMgr.getCurrentScene():getFormByName("UIItemCompound");
            if uiForm then
                uiForm:redraw();
            end
        end
    end);
end

-- 获取商城冈布奥碎片的id
function UIBuyMaterial:getScrapIds()
    local ids = {};
    -- 需要添加上活动区间的碎片
    local finalList = MarketM.getSellScrapList(true);
    if #finalList == 0 then
        return ids;
    end

    for i = 1, #finalList do
        local info = finalList[i].bonus;
        table.insert(ids, info[1][2]);
    end

    return ids;
end

-- 判断可以直接购买
function UIBuyMaterial:setCanBuy()
    local group_id = ItemM.query(self.classId, "group");

    if group_id ~= 13 and group_id ~= 38 then
        self.canBuy = true;
        return;
    end

    local ids = self:getScrapIds();
    local materialId = self.materialList[1].classId;

    if table.indexOf(ids, materialId) ~= -1 then
        self.canBuy = true;
        return;
    end

    self.canBuy = false;
end

-- 适配
function UIBuyMaterial:resize()
    local node = self.node;

    -- bg充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

